package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strings"
	"time"

	"github.com/gorilla/websocket"
)

// 注意: 运行前需要安装依赖
// 1. 初始化go.mod文件(如果没有): go mod init crawler
// 2. 安装依赖: go get github.com/gorilla/websocket

// 定义存储球队数据的结构体
type TeamData struct {
	TeamName string   `json:"team_name"`
	Score    int      `json:"score"`
	Players  []Player `json:"players"`
	// 可根据实际返回数据添加更多字段
}

type Player struct {
	Name  string `json:"name"`
	Stats string `json:"stats"`
}

func main() {
	// 目标URL
	url := "wss://i875ob.zmn2658.com/(S(Tesqedixa139b688027b4f3fbd17ee0acace2751))/NewIndex?lang=cs&scmt=tab02&ssmt=tab02"

	// 创建一个上下文，用于控制连接超时
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// 创建WebSocket连接
	conn, _, err := websocket.DefaultDialer.DialContext(ctx, url, http.Header{
		"User-Agent": []string{"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"},
		"Origin":     []string{"https://i875ob.zmn2658.com"},
	})
	if err != nil {
		log.Fatalf("Failed to connect to WebSocket server: %v", err)
	}
	defer conn.Close()

	// 发送握手消息或初始请求（根据网站要求）
	handshakeMsg := map[string]interface{}{
		"type": "handshake",
		"data": "basketball_data_request",
	}
	if err := conn.WriteJSON(handshakeMsg); err != nil {
		log.Fatalf("Failed to send handshake message: %v", err)
	}

	// 创建一个通道来接收和处理消息
	done := make(chan struct{})

	// 启动一个goroutine来接收消息
	go func() {
		defer close(done)
		for {
			// 读取消息类型，消息数据
			messageType, message, err := conn.ReadMessage()
			if err != nil {
				log.Printf("Error reading message: %v", err)
				return
			}

			// 处理文本消息
			if messageType == websocket.TextMessage {
				// 解析JSON数据
				var data map[string]interface{}
				if err := json.Unmarshal(message, &data); err != nil {
					log.Printf("Error parsing JSON: %v", err)
					continue
				}

				// 检查是否是篮球数据
				if dataType, ok := data["type"].(string); ok && strings.Contains(dataType, "basketball") {
					// 提取球队数据
					if teams, ok := data["teams"].([]interface{}); ok {
						for _, team := range teams {
							teamMap := team.(map[string]interface{})
							teamName := teamMap["name"].(string)
							score := int(teamMap["score"].(float64))

							// 打印球队信息
							fmt.Printf("Team: %s, Score: %d\n", teamName, score)

							// 可以在这里添加更多处理逻辑，如存储到数据库等
						}
					}
				}
			}
		}
	}()

	// 保持程序运行一段时间以接收数据
	timer := time.NewTimer(30 * time.Second)
	select {
	case <-done:
	case <-timer.C:
		fmt.Println("Timeout, closing connection")
	}
}
